package com.micro.ai.template.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.template.entity.TemplateRating;
import com.micro.ai.template.service.TemplateRatingService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.Map;

/**
 * 模板评分Controller
 *
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@RestController
@RequestMapping("/api/template/ratings")
@RequiredArgsConstructor
@Tag(name = "模板评分管理", description = "模板评分相关接口")
public class TemplateRatingController {

    private final TemplateRatingService templateRatingService;

    @PostMapping
    @PreAuthorize("hasAuthority('template:rating:create')")
    @Operation(summary = "创建或更新评分", description = "用户为模板评分或更新评分")
    @ApiResponses({
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "200", description = "评分成功",
                    content = @Content(schema = @Schema(implementation = TemplateRating.class))),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "400", description = "评分参数错误"),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "403", description = "权限不足")
    })
    public ApiResponse<TemplateRating> createOrUpdateRating(
            @io.swagger.v3.oas.annotations.parameters.RequestBody(description = "评分信息", required = true)
            @Valid @RequestBody TemplateRating templateRating,
            Authentication authentication) {
        // 从认证信息中获取用户ID
        String userId = authentication.getName();
        templateRating.setUserId(userId);
        
        log.info("评分请求, templateId: {}, userId: {}", templateRating.getTemplateId(), userId);
        return ApiResponse.success(templateRatingService.createOrUpdateRating(templateRating));
    }

    @GetMapping("/template/{templateId}")
    @Operation(summary = "查询模板评分列表", description = "分页查询指定模板的所有评分")
    public ApiResponse<IPage<TemplateRating>> getRatingsByTemplateId(
            @Parameter(description = "模板ID") @PathVariable String templateId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size) {
        
        Page<TemplateRating> page = new Page<>(current, size);
        return ApiResponse.success(templateRatingService.getRatingsByTemplateId(templateId, page));
    }

    @GetMapping("/template/{templateId}/user")
    @PreAuthorize("hasAuthority('template:rating:query')")
    @Operation(summary = "查询用户评分", description = "获取当前用户对指定模板的评分")
    public ApiResponse<TemplateRating> getUserRating(
            @Parameter(description = "模板ID") @PathVariable String templateId,
            Authentication authentication) {
        String userId = authentication.getName();
        return ApiResponse.success(templateRatingService.getUserRating(templateId, userId));
    }

    @DeleteMapping("/{ratingId}")
    @PreAuthorize("hasAuthority('template:rating:delete')")
    @Operation(summary = "删除评分", description = "删除自己的评分")
    public ApiResponse<Void> deleteRating(
            @Parameter(description = "评分ID") @PathVariable String ratingId,
            Authentication authentication) {
        String userId = authentication.getName();
        log.info("删除评分请求, ratingId: {}, userId: {}", ratingId, userId);
        templateRatingService.deleteRating(ratingId, userId);
        return ApiResponse.<Void>success(null);
    }

    @GetMapping("/template/{templateId}/average")
    @Operation(summary = "查询平均评分", description = "获取模板的平均评分和总评分数")
    public ApiResponse<Map<String, Object>> getAverageRating(
            @Parameter(description = "模板ID") @PathVariable String templateId) {
        return ApiResponse.success(templateRatingService.getAverageRating(templateId));
    }

    @GetMapping("/template/{templateId}/distribution")
    @Operation(summary = "查询评分分布", description = "获取模板评分的星级分布")
    public ApiResponse<Map<Integer, Long>> getRatingDistribution(
            @Parameter(description = "模板ID") @PathVariable String templateId) {
        return ApiResponse.success(templateRatingService.getRatingDistribution(templateId));
    }
}

